
package test.app.audit;

import java.util.Date;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.ui.WebAuthenticationDetails;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class AuditLogger extends HibernateDaoSupport implements IAuditLogger{
				
    public void addEntityAuditRecord(IAuditable auditable, OperationType logTipi,RecordType rtype) {
    
    	EntityAuditRecord auditRecord = createEntityAuditRecord(auditable,logTipi,rtype);
        
    	getHibernateTemplate().save(auditRecord);
    }
            
    private EntityAuditRecord createEntityAuditRecord(IAuditable auditable, OperationType type,RecordType rtype) {
    	EntityAuditRecord auditRecord = new EntityAuditRecord();
    	auditRecord.setOperationType(type);
    	auditRecord.setOperationKey(auditable.getClass().getName()+ ":" + (auditable).getPK());
    	auditRecord.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
    	auditRecord.setOperationDate(new Date());
    	auditRecord.setMessage(auditable.getAuditMessage());
    	auditRecord.setAuditRecordType(rtype);
    	Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    	WebAuthenticationDetails wa = (WebAuthenticationDetails) auth.getDetails();
    	auditRecord.setIpUsuario(wa.getRemoteAddress());
    	return auditRecord;
    }



	

}
